"use client"
import React, { useEffect, useState } from "react";
import { Button, Input, Form, CollapseProps, Collapse, Drawer, Radio } from "antd";
import { CaretRightOutlined } from "@ant-design/icons";
import styles from './index.module.css'
import baseInformationClass from "@/components/properties-panel-extension/components/index.module.css";
import ProcessMessageView from "./component/ProcessMessage";
import ProcessErrorView from "./component/ProcessError";
import ProcessSignalView from "./component/ProcessSignal";
import ProcessUpgradeView from "./component/ProcessUpgrade";
import { generateUniqueId } from "@/utils/Z";

interface MyComponentProps {
    bpmnInstance: any;
}

interface ExecutionListenerElement {
    $type: string;
    event: string;
    class?: string;
    expression?: string;
    delegateExpression?: string;
}

interface EventConfig {
    eventDefinitionType: any;
    messageName?: string;
    signalName?: string;
    timerDefinitionType?: any;
    timerDefinition?: string;
}

const ProcessConfigurationView: React.FC<MyComponentProps> = (props: any) => {
    const { bpmnInstance } = props
    const { modeling, modeler, moddle, bpmnElement = {} } = bpmnInstance
    const [baseInfo, setBaseInfo] = useState<any>();
    const [openEvent, setOpenEvent] = useState(false);
    const [eventData, setEventData] = useState({
        messages: [],
        errors: [],
        signals: [],
        upgrades: []
    });

    // 1. 提取并分类事件数据（初始化+更新时调用）
    useEffect(() => {
        if (bpmnElement.businessObject) {
            setBaseInfo({ ...bpmnElement.businessObject });
        }
        updateEventData(); // 封装成方法，方便删除后复用
    }, [bpmnElement.businessObject, modeler]);

    // 2. 封装事件数据更新方法（删除后需重新获取数据）
    const updateEventData = () => {
        const definitions = modeler.getDefinitions();
        if (definitions?.rootElements) {
            setEventData({
                messages: definitions.rootElements.filter((el: any) => el.$type === 'bpmn:Message'),
                errors: definitions.rootElements.filter((el: any) => el.$type === 'bpmn:Error'),
                signals: definitions.rootElements.filter((el: any) => el.$type === 'bpmn:Signal'),
                upgrades: definitions.rootElements.filter((el: any) => el.$type === 'bpmn:Escalation')
            });
        }
    };

    const [form] = Form.useForm();
    const [type, setType] = useState<string>('');
    const [formData, setFormData] = useState<any>({});

    // 3. 新增：打开抽屉（自动生成ID）
    const showDrawer = (e: React.MouseEvent<HTMLElement>, type: string) => {
        e.stopPropagation();
        setType(type);
        setOpenEvent(true);
        form.setFieldsValue({ id: generateUniqueId(type) });
    };

    // 4. 编辑：回显数据
    const EditClick = (record: any, type: string) => {
        setType(type);
        setOpenEvent(true);
        const prefix = type.charAt(0).toUpperCase() + type.slice(1);
        form.setFieldsValue({
            id: record.id?.replace(`${prefix}_`, ''), // 移除前缀（如Message_）
            name: record.name,
            ...(type === 'error' && { errorCode: record.errorCode }),
            ...(type === 'upgrade' && { escalationCode: record.escalationCode })
        });
    };

    // 5. 新增：删除事件元素（传递给子组件）
    const handleDeleteEvent = (record: any, type: string) => {
        try {
            const definitions = modeler.getDefinitions();
            // 过滤掉要删除的元素
            const newRootElements = definitions.rootElements.filter(
                (el: any) => el.id !== record.id
            );
            // 更新BPMN模型
            modeling.updateModdleProperties(bpmnElement, definitions, {
                rootElements: newRootElements
            });
            // 重新获取数据，更新表格
            updateEventData();
        } catch (error) {
            console.error("删除事件失败：", error);
        }
    };

    const items: CollapseProps['items'] = [
        {
            key: 'message',
            label: (
                <div className="w-full flex justify-between items-center">
                    <div>消息列表 <span className="text-gray-500 text-sm">({eventData.messages.length})</span></div>
                    <Button
                        size="small"
                        color="primary"
                        variant="text"
                        onClick={(e) => showDrawer(e, 'message')}
                    >
                        添加消息
                    </Button>
                </div>
            ),
            // 6. 传递3个核心属性给子组件：BPMN实例、数据、编辑/删除回调
            children: <ProcessMessageView
                bpmnInstance={bpmnInstance}
                data={eventData.messages} // 传递消息数据
                EditClick={(record) => EditClick(record, "message")} // 编辑回调
                onDelete={(record) => handleDeleteEvent(record, "message")} // 删除回调
            />,
            styles: { body: { padding: 0 } }
        },
        // 其他类型（error/signal/upgrade）同理，这里省略...
        {
            key: 'error',
            label: (
                <div className="w-full flex justify-between items-center">
                    <div>错误列表 <span className="text-gray-500 text-sm">({eventData.errors.length})</span></div>
                    <Button
                        size="small"
                        color="primary"
                        variant="text"
                        onClick={(e) => showDrawer(e, 'error')}
                    >
                        添加错误
                    </Button>
                </div>
            ),
            children: <ProcessErrorView
                bpmnInstance={bpmnInstance}
                data={eventData.errors}
                EditClick={(record) => EditClick(record, "error")}
                onDelete={(record) => handleDeleteEvent(record, "error")}
            />,
            styles: { body: { padding: 0 } }
        },
          {
            key: 'signal',
            label: (
                <div className="w-full flex justify-between items-center">
                    <div>信号列表 <span className="text-gray-500 text-sm">({eventData.signals.length})</span></div>
                    <Button
                        size="small"
                        color="primary"
                        variant="text"
                        onClick={(e) => showDrawer(e, 'signal')}
                    >
                        添加信号
                    </Button>
                </div>
            ),
            children: <ProcessSignalView
                bpmnInstance={bpmnInstance}
                data={eventData.signals}
                EditClick={(record) => EditClick(record, "signal")}
                onDelete={(record) => handleDeleteEvent(record, "signal")}
            />,
            styles: { body: { padding: 0 } }
        },
        {
            key: 'upgrade',
            label: (
                <div className="w-full flex justify-between items-center">
                    <div>升级列表 <span className="text-gray-500 text-sm">({eventData.upgrades.length})</span></div>
                    <Button
                        size="small"
                        color="primary"
                        variant="text"
                        onClick={(e) => showDrawer(e, 'upgrade')}
                    >
                        添加升级
                    </Button>
                </div>
            ),
            children: <ProcessUpgradeView
                bpmnInstance={bpmnInstance}
                data={eventData.upgrades}
                EditClick={(record) => EditClick(record, "upgrade")}
                onDelete={(record) => handleDeleteEvent(record, "upgrade")}
            />,
            styles: { body: { padding: 0 } }
        },
        // signal和upgrade组件同理，按上述格式补充...
    ];

    const onValuesChange = (changedValues: any, allValues: any) => {
        setFormData(allValues);
    };

    // 7. 提交（新增/编辑）事件
    const handleSubmit = async () => {
        try {
            const values = await form.validateFields();
            let newElement: any;
            const prefix = type.charAt(0).toUpperCase() + type.slice(1);

            // 根据类型创建对应的BPMN元素
            switch (type) {
                case 'message':
                    newElement = moddle.create('bpmn:Message', {
                        name: values.name,
                        id: `${prefix}_${values.id}`, // 拼接前缀（如Message_xxx）
                    });
                    break;
                case 'error':
                    newElement = moddle.create('bpmn:Error', {
                        name: values.name,
                        errorCode: values.errorCode,
                        id: `${prefix}_${values.id}`,
                    });
                    break;
                // signal和upgrade同理，按上述格式补充...
                default:
                    return;
            }

            const definitions = modeler.getDefinitions();
            // 先删除旧元素（编辑场景），再添加新元素
            const newRootElements = definitions.rootElements
                .filter((el: any) => el.id !== `${prefix}_${values.id}`) // 去重
                .concat(newElement);

            // 更新BPMN模型
            modeling.updateModdleProperties(bpmnElement, definitions, {
                rootElements: newRootElements
            });

            // 关闭抽屉+重置表单+更新数据
            setOpenEvent(false);
            form.resetFields();
            updateEventData();
        } catch (error) {
            console.error("提交事件失败：", error);
        }
    };

    return (
        <div className={baseInformationClass.listenerContainer}>
            <Collapse
                expandIconPosition="end"
                expandIcon={({ isActive }) => <CaretRightOutlined rotate={isActive ? 90 : 0} />}
                items={items}
            />
            <Drawer
                title={`${type ? type.charAt(0).toUpperCase() + type.slice(1) : '创建'}事件`}
                closable={{ 'aria-label': 'Close Button' }}
                mask={false}
                onClose={() => {
                    setOpenEvent(false);
                    form.resetFields();
                }}
                open={openEvent}
                footer={[
                    <Button key="cancel" onClick={() => {
                        setOpenEvent(false);
                        form.resetFields();
                    }}>
                        取消
                    </Button>,
                    <Button key="submit" type="primary" onClick={handleSubmit}>
                        确认
                    </Button>,
                ]}
            >
                <Form form={form} name="editProcessConfiguration" onValuesChange={onValuesChange}>
                    <Form.Item
                        label="ID"
                        name="id"
                        rules={[{ required: true, message: '请输入ID' }]}
                    >
                        <Input placeholder="自动生成的唯一ID" />
                    </Form.Item>
                    <Form.Item
                        label="名称"
                        name="name"
                        rules={[{ required: true, message: '请输入名称' }]}
                    >
                        <Input />
                    </Form.Item>
                    {type === 'error' && (
                        <Form.Item
                            label="错误代码"
                            name="errorCode"
                            rules={[{ required: true, message: '请输入错误代码' }]}
                        >
                            <Input />
                        </Form.Item>
                    )}
                    {/* 其他类型的表单项（signal/upgrade）同理补充 */}
                </Form>
            </Drawer>
        </div>
    );
};

export default ProcessConfigurationView;